package com.senyint.imsdk.packet;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.jivesoftware.smack.packet.PacketExtension;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * 确认消息是否发送成功到服务器<br>
 * @author penghui
 */
public class DeliverySent implements PacketExtension
{
    public static final String NAMESPACE = "urn:syt:snt";
    public static final String ELEMENT = "snt";
    public static final String CHILD_ELEMENT = "key";
    private String key = null ; 

    public DeliverySent(){}
    
    public DeliverySent(String key)
    {
        this.key = key;
    }

    public String getId()
    {
        return key;
    }

    @Override
    public String getElementName()
    {
        return ELEMENT;
    }

    @Override
    public String getNamespace()
    {
        return NAMESPACE;
    }
    

    /**
     * 如果id为null，则意味着这是一个请求信息
     */
    @Override
    public String toXML()
    {
    	if(key == null){
    		return "<"+ELEMENT+" xmlns='" + NAMESPACE + "' />";
    	}
    	StringBuffer sb = new StringBuffer();
    	sb.append("<").append(ELEMENT).append( " xmlns='").append(NAMESPACE).append("'>");
    	sb.append("<key>").append(key).append("</key>");
    	sb.append("</").append(ELEMENT).append(">");
    	return sb.toString();
    }

    public static DeliverySent parse(String xml) {
    	DeliverySent dse = new DeliverySent();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
            Element root = document.getDocumentElement();
            NodeList nodeList = root.getChildNodes();
            int size = nodeList.getLength();
            for (int i = 0; i < size; i++) {
                Node node = nodeList.item(i);
                String nodeName = node.getNodeName();
//                String value = node.getTextContent();
                if (nodeName.equals(CHILD_ELEMENT)) {
                	dse.key = node.getTextContent();
                } 
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return dse;
    }

    
}
